/*
+--------------------------------------------------------------------------
|   Mblog [#RELEASE_VERSION#]
|   ========================================
|   Copyright (c) 2014, 2015 mtons. All Rights Reserved
|   http://www.mtons.com
|
+---------------------------------------------------------------------------
*/
package mblog.web.controller.admin;

import mblog.base.lang.Consts;
import mblog.base.upload.FileRepoFactory;
import mblog.base.utils.PushSiteMapUtil;
import mblog.base.utils.WebUtils;
import mblog.core.biz.PostBiz;
import mblog.core.data.Attach;
import mblog.core.data.Post;
import mblog.core.data.xml.SiteMap;
import mblog.core.persist.service.PostService;
import mblog.web.controller.BaseController;
import mtons.modules.lang.Const;
import mtons.modules.pojos.Data;
import mtons.modules.pojos.Paging;
import mtons.modules.utils.FileNameUtils;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.Marshaller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.stream.StreamResult;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author langhsu
 */
@Controller("mng_post_ctl")
@RequestMapping("/admin/posts")
public class PostsController extends BaseController {
    @Autowired
    private PostService postService;
    @Autowired
    private PostBiz postBiz;
    @Autowired
    private Marshaller marshaller;

    @RequestMapping("/list")
    public String list(Integer pn, String title, ModelMap model, HttpServletRequest request) {
        long id = ServletRequestUtils.getLongParameter(request, "id", Const.ZERO);
        int group = ServletRequestUtils.getIntParameter(request, "group", Const.ZERO);

        Paging page = wrapPage(pn);

        postService.paging4Admin(page, id, title, group);
        model.put("page", page);
        model.put("title", title);
        model.put("id", id);
        model.put("group", group);
        return "/admin/posts/list";
    }

    /**
     * 跳转到文章编辑方法
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String toUpdate(Long id, ModelMap model) {
        Post ret = postService.get(id);
        model.put("view", ret);
        return "/admin/posts/update";
    }

    /**
     * 更新文章方法
     *
     * @return
     * @author LBB
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String subUpdate(Post p) {
        if (p != null) {
            postService.update(p);
        }
        return "redirect:/admin/posts/list";
    }

    @RequestMapping("/featured")
    public
    @ResponseBody
    Data featured(Long id, HttpServletRequest request) {
        Data data = Data.failure("操作失败");
        int featured = ServletRequestUtils.getIntParameter(request, "featured", Consts.FEATURED_ACTIVE);
        if (id != null) {
            try {
                postBiz.updateFeatured(id, featured);
                data = Data.success("操作成功", Data.NOOP);
            } catch (Exception e) {
                data = Data.failure(e.getMessage());
            }
        }
        return data;
    }

    @RequestMapping("/delete")
    public
    @ResponseBody
    Data delete(@RequestParam("id") List<Long> id) {
        Data data = Data.failure("操作失败");
        if (id != null) {
            try {
                postBiz.delete(id);
                data = Data.success("操作成功", Data.NOOP);
            } catch (Exception e) {
                data = Data.failure(e.getMessage());
            }
        }
        return data;
    }

    @RequestMapping(value = "download", method = RequestMethod.GET)
    public void download(Long id, String color, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Post post = postService.get(id);

        Attach album = post.getAlbum();
        if (album == null) {
            throw new RuntimeException("post album can not null");
        }
        File downloadImg = getDownloadImg(request, album, color);
        OutputStream os = response.getOutputStream();
        try {
            response.reset();
            String fileName = WebUtils.encodeChineseDownloadFileName(request, post.getTitle()) + "." + getExt(downloadImg.getName());//为了解决中文名称乱码问题
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setContentType("application/octet-stream; charset=utf-8");
            os.write(FileUtils.readFileToByteArray(downloadImg));
            os.flush();
        } finally {
            if (os != null) {
                os.close();
            }
        }

    }


    public File getDownloadImg(HttpServletRequest request, Attach album, String color) throws IOException {
        ServletContext servletContext = request.getSession().getServletContext();
        String root = servletContext.getRealPath("/");

        File srcFile = getSrcFile(album, root);

        String name = FileNameUtils.genFileName(getExt(srcFile.getName()));
        String path = appContext.getTempDir() + "/" + name;
        File temp = new File(root + path);
        if (!temp.getParentFile().exists()) {
            temp.getParentFile().mkdirs();
        }

        FileUtils.copyFile(srcFile, temp);
        watermarkImage(temp, temp, new File(root + "/store/font_" + color + "_img.png"));

        return temp;
    }

    private File getSrcFile(Attach album, String root) {
        String original = album.getOriginal();
        if (!original.startsWith("http://") && !original.startsWith("https://")) {
            return new File(root + original);
        }
        String ext = original.substring(original.lastIndexOf("."));
        String tempName = appContext.getTempDir() + "/" + UUID.randomUUID().toString() + ext;
        File file = new File(root + tempName);
        try {
            getRemoteFile(album.getOriginal(), file);
            return file;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void getRemoteFile(String strUrl, File file) throws IOException {
        URL url = new URL(strUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        DataInputStream input = new DataInputStream(conn.getInputStream());
        DataOutputStream output = new DataOutputStream(new FileOutputStream(file));
        byte[] buffer = new byte[1024 * 8];
        int count = 0;
        while ((count = input.read(buffer)) > 0) {
            output.write(buffer, 0, count);
        }
        output.close();
        input.close();
    }

    protected void watermarkImage(File ori, File dest, File watermark) throws IOException {
        BufferedImage src = ImageIO.read(ori); // 读入文件
        int width = src.getWidth();
        int height = src.getHeight();
        Thumbnails.of(ori)
                .size(width, height)
                .watermark(Positions.BOTTOM_LEFT, ImageIO.read(watermark), 1f)
                .outputQuality(1f)
                .toFile(dest);
    }


    protected String getExt(String filename) {
        int pos = filename.lastIndexOf(".");
        return filename.substring(pos + 1);
    }

    /**
     * 主动推送给百度
     */
    @RequestMapping(value = "/pushBaiDu", method = RequestMethod.GET)
    @ResponseBody
    public String pushBaiDu(@RequestParam("ids") List<Long> ids) {
        List<String> urls = new ArrayList<>();
        for (Long id : ids) {
            String url = "http://www.xianshiyue.com/view/" + id;
            urls.add(url);
        }
        if (!urls.isEmpty()) {
            return PushSiteMapUtil.push(urls);
        }
        return "urls不能为空";
    }


    @RequestMapping("/sitemap")
    @ResponseBody
    public Data sitemap(HttpServletRequest request) {
        ServletContext servletContext = request.getSession().getServletContext();
        String root = servletContext.getRealPath("/");

        Data data = Data.success("操作成功");
        SiteMap sitemap = postService.sitemap();
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(root + "sitemap.xml");
            marshaller.marshal(sitemap, new StreamResult(fos));
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            data = Data.failure("操作失败,不能找到文件");
        } catch (IOException e) {
            e.printStackTrace();
            data = Data.failure("操作失败,IOException");
        }
        return data;
    }


}
